<?php


namespace app\api\controller;
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

use app\api\Api;
use app\api\controller\Jwt as Jwt;
use think\Db;
use think\Request;

/**
 * Class Order
 * @package app\api\controller
 */
class Order extends Api
{

    private static $uid;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $token = input('server.HTTP_AUTHORIZATION');
        $result = Jwt::verifyToken($token);
        if (!$result) {
            echo json_encode(["code" => 400102, "msg" => '请先登录'], JSON_UNESCAPED_UNICODE);
            die();
        }
        self::$uid = $result['sub'];   //给类的静态属性赋值 用户id
    }

    /**
     * 获取价格
     *dev.ziwudiche.com/api/order/getprice
     *
     */
    public function getprice()
    {

        $vehicle_list = input('vehicle_list');
        $vehicle_data=json_decode($vehicle_list,true);
        $startcitygradecoefficient = $this->getstartcitygradecoefficient();
        $endcitygradecoefficient = $this->getendcitygradecoefficient();
        $distance = $this->getdistance();
//        echo "<pre>";
//        die(var_dump($distance,$vehicle_data));
//        echo "</pre>";

        foreach ($vehicle_data as $v){
                $pricecoefficient = $this->getcarpricecoefficient($v['vehicle_value']);
                $sizecoefficient = $this->getcarsizecoefficient($v['separation']);
                $departure_mode=$v['departure_mode'];
                $receiving_mode=$v['receiving_mode'];
//                $amount=$v['amount'];
                if ($startcitygradecoefficient==1){
                    switch ($departure_mode){
                        case 1:$startcost=300;break;
                        case 2:$startcost=500;break;
                        case 3:$startcost=0;break;
                    }
                }
                if ($startcitygradecoefficient==1.1){
                    switch ($departure_mode){
                        case 1:$startcost=200;break;
                        case 2:$startcost=400;break;
                        case 3:$startcost=0;break;
                    }
                }
                if ($startcitygradecoefficient==1.2){
                    switch ($departure_mode){
                        case 1:$startcost=200;break;
                        case 2:$startcost=300;break;
                        case 3:$startcost=0;break;

                    }
                }
                if ($endcitygradecoefficient==1){
                    switch ($receiving_mode){
                        case 1:$endcost=300;break;
                        case 2:$endcost=500;break;
                        case 3:$endcost=0;break;
                    }
                }
                if ($endcitygradecoefficient==1.2){
                    switch ($receiving_mode){
                        case 1:$endcost=200;break;
                        case 2:$endcost=400;break;
                        case 3:$endcost=0;break;
                    }
                }
                if ($endcitygradecoefficient==1.4){
                    switch ($receiving_mode){
                        case 1:$endcost=200;break;
                        case 2:$endcost=300;break;
                        case 3:$endcost=0;break;
                    }
                }
                if ($distance <= 100) {
                    $price = 1000;
                    $this->return_arr["data"][]=[
                        "price" => $price,
                        "startcost"=>0,
                        "endcost"=>0
                    ];
                } else {

                    $price = $distance * $startcitygradecoefficient * $endcitygradecoefficient * $pricecoefficient * $sizecoefficient;
                    $this->return_arr["data"][]=[
                        "price" => $price,
                        "startcost"=>$startcost,
                        "endcost"=>$endcost
                    ];
                }
        }
        $this->echoResult($this->return_arr);
    }

    /**
     * 获取路程
     *dev.ziwudiche.com/api/order/getdistance
     *
     * @param array $start_addr_code 起始地行政编码
     * @param array $end_addr_code 目的地行政编码
     */

    public function getdistance()
    {
        $start_addr_code = input('start_addr_code/a');
        $start_pro = Db::name('pro')->where('id', $start_addr_code[0])->value('name');
        $start_city = Db::name('city')->where('id', $start_addr_code[1])->value('name');
        $start = $start_pro . $start_city;
        $app_key = '5a14fc918b8ea16836ddce03a1501fa5';
        $start_url = "http://restapi.amap.com/v3/geocode/geo?address=$start&output=JSON&key=$app_key";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $start_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result1 = curl_exec($ch);

        $arr1 = json_decode($result1, true);
        curl_close($ch);
        $start_Longitude_latitude = $arr1['geocodes'][0]['location'];

        $end_addr_code = input('end_addr_code/a');
        $end_pro = Db::name('pro')->where('id', $end_addr_code[0])->value('name');
        $end_city = Db::name('city')->where('id', $end_addr_code[1])->value('name');
        $end = $end_pro . $end_city;
        $end_url = "http://restapi.amap.com/v3/geocode/geo?address=$end&output=JSON&key=$app_key";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $end_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result2 = curl_exec($ch);

        curl_close($ch);
        $arr2 = json_decode($result2, true);
        $end_Longitude_latitude = $arr2['geocodes'][0]['location'];

        $distance_url = "http://restapi.amap.com/v4/direction/truck?origin=$start_Longitude_latitude&destination=$end_Longitude_latitude&size=4&height=4.8&weight=50&nosteps=1&key=$app_key";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $distance_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result3 = curl_exec($ch);
        curl_close($ch);
        $arr3 = json_decode($result3, true);
        $distance = intval($arr3['data']['route']['paths'][0]['distance'] / 1000);
        return $distance;
    }

    //获取车价系数
    private function getcarpricecoefficient($carprice)
    {
//        $carprice = input('vehicle_value');
        if ($carprice==1){
            return 1;
        }
        if ($carprice==2){
            return 1.3;
        }
        if ($carprice==3){
            return 2;
        }
    }

    //获取车型系数
    private function getcarsizecoefficient($carseparation)
    {
//        $carseparation = input('separation');
        $sizetype = Db::name('vehicle_separation')->where('separation', $carseparation)->value('sizetype');

        $small = array("紧凑型车", "中型车", "小型车", "微型车", "紧凑型SUV", "小型SUV");
        $middle = array("中大型车", "中型SUV", "中大型SUV", "紧凑型MPV", "面包车", "小型MPV", "中型MPV", "SUV");
        $big = array("MPV", "跑车", "皮卡", "大型MPV", "全尺寸SUV", "豪华车", "小型跑车", "大型跑车", "中型跑车");
        if (in_array($sizetype, $small)) {
            return 1;
        }
        if (in_array($sizetype, $middle)) {
            return 1.05;
        }
        if (in_array($sizetype, $big)) {
            return 1.1;
        }
    }

    //获取发车城市等级系数
    public function getstartcitygradecoefficient()
    {
        $start_addr_code = input('start_addr_code/a');
        $id = $start_addr_code[1];
        $grade = Db::name('city')->where('id', $id)->value('grade');
        if ($grade == 1) {
            return 1;
        }
        if ($grade == 2) {
            return 1.1;
        }
        if ($grade == 3) {
            return 1.2;
        }
    }

    //获取收车城市等级系数
    public function getendcitygradecoefficient()
    {
        $end_addr_code = input('end_addr_code/a');
        $id = $end_addr_code[1];
        $grade = Db::name('city')->where('id', $id)->value('grade');
        if ($grade == 1) {
            return 1;
        }
        if ($grade == 2) {
            return 1.2;
        }
        if ($grade == 3) {
            return 1.4;
        }
    }

    /**
     * 创建订单
     *dev.ziwudiche.com/api/order/createorder
     * @param string $departureid 发车人地址信息id
     * @param string $receiverid 收车人地址信息id
     * @param string $price  总价
     * @param string $remarks  订单备注
     * @param json $vehicle_list   车辆信息
     *
     */
    public function createorder()
    {
        $uid = self::$uid;
        $departureid = input('departureid');
        $receiverid = input('receiverid');
        $remarks =  input('remarks');
        $price = input('price');
        $ctime = date('Y-m-d H:i:s', time());
        $data = [
            "uid" => $uid,
            "receiverid" => $receiverid,
            "departureid" => $departureid,
            "order_number" => $uid . date('Ymdhis', time()),
            "remarks" => $remarks,
            "price" => $price,
            "ctime" => $ctime,
        ];
        $vehicle_list = input('vehicle_list');
        $vehicle_data=json_decode($vehicle_list,true);
        // 启动事务
        Db::startTrans();
        try{

            $oid = Db::name('order')->insertGetId($data);
//            echo "<pre>";
//            die(var_dump($vehicle_data));
//            echo "</pre>";

            foreach ($vehicle_data as $v){
                     $car_data=[
                        "oid"=>$oid,
                        "brand"=>$v['brand'],
                        "separation"=>$v['separation'],
//
//
//
//
//
//                        "start"=>$v['start'],
                        "departure_mode"=>$v['departure_mode'],
                        "receiving_mode"=>$v['receiving_mode'],
//                        "end"=>$v['end'],
                         "uid"=>$uid,
                         "frame_number"=>$v['frame_number'],
                    ];

//
//                echo "<pre>";
//                die(var_dump($car_data));
//                echo "</pre>";
               $id= Db::name('vehicle_information')->insertGetId($car_data);

            }
            // 提交事务
            Db::commit();
            echo json_encode(["code" => 200, "msg" => '创建订单成功','oid'=>$oid], JSON_UNESCAPED_UNICODE);die();
        } catch (\Exception $e) {
        // 回滚事务
            Db::rollback();
            echo json_encode(["code" => 400, "msg" => '创建订单失败'], JSON_UNESCAPED_UNICODE);die();

        }

    }

    /**
     *获取订单
     * dev.ziwudiche.com/api/order/getorders
     * @param string $status
     * 订单状态:1=待付款,2=待验车,3=待收车, 0=全部
     */
    public function getorders()
    {
        $status = input('status');
        $uid = self::$uid;
            switch ($status) {
                case "0":
                    $order_data = Db::name('order')->where('uid', $uid)->order('id desc')->select();
                    foreach ($order_data as &$v){
                        $oid=$v['id'];
                        $vehicle_data=Db::name('vehicle_information')->where('oid',$oid)->select();
//                        $amount=null;
//                        foreach ($vehicle_data as $vv){
//                            $amount+=$vv['amount'];
//                        }
//                        $v['amount']=$amount;
                    }

                    echo json_encode(["code" => 200, "data" => $order_data], JSON_UNESCAPED_UNICODE);
                    break;
                case "1":
                    $order_data = Db::name('order')->where('uid', $uid)->order('id desc')->where('status', 1)->select();
                    foreach ($order_data as &$v){
                        $oid=$v['id'];
                        $vehicle_data=Db::name('vehicle_information')->where('oid',$oid)->select();
                        $amount=null;
//                        foreach ($vehicle_data as $vv){
//                            $amount+=$vv['amount'];
//                        }
//                        $v['amount']=$amount;
                    }
                    echo json_encode(["code" => 200, "data" => $order_data], JSON_UNESCAPED_UNICODE);
                    break;
                case "2":
                    $order_data = Db::name('order')->where('uid', $uid)->order('id desc')->where('status', 2)->select();
                    foreach ($order_data as &$v){
                        $oid=$v['id'];
                        $vehicle_data=Db::name('vehicle_information')->where('oid',$oid)->select();
//                        $amount=null;
//                        foreach ($vehicle_data as $vv){
//                            $amount+=$vv['amount'];
//                        }
//                        $v['amount']=$amount;
                    }
                    echo json_encode(["code" => 200, "data" => $order_data], JSON_UNESCAPED_UNICODE);
                    break;
                case "3":
                    $order_data = Db::name('order')->where('uid', $uid)->order('id desc')->where('status', 3)->select();
                    foreach ($order_data as &$v){
                        $oid=$v['id'];
                        $vehicle_data=Db::name('vehicle_information')->where('oid',$oid)->select();
                        $amount=null;
//                        foreach ($vehicle_data as $vv){
//                            $amount+=$vv['amount'];
//                        }
//                        $v['amount']=$amount;
                    }
                    echo json_encode(["code" => 200, "data" => $order_data], JSON_UNESCAPED_UNICODE);
                    break;
                default:
                    echo json_encode(["code" => 400, "msg" => '获取失败'], JSON_UNESCAPED_UNICODE);
            }
    }


    /**
     *获取用户订单详情
     *
     * dev.ziwudiche.com/api/order/getorderdetail
     * @param string $oid  订单id
     *
     */
    public function getorderdetail()
    {
        // 启动事务
        Db::startTrans();
        try{
            $oid = input('oid');
            $order_data = Db::name('order')->where('id', $oid)->find();
            $departureid=$order_data['departureid'];
            $receiverid=$order_data['receiverid'];
            $departure_data = Db::name('address_information')->where('id',  $departureid)->find();
            $receiver_data = Db::name('address_information')->where('id',  $receiverid)->find();
            $vehicle_data = Db::name('vehicle_information')->where('oid', $oid)->select();
            foreach ($vehicle_data as &$v){
                $logo=Db::name("vehicle_brand")->where('brand',$v['brand'])->value('logo');
                $v['logo']=$logo;
            }
        // 提交事务
            Db::commit();
            echo json_encode(["code" => 200, "msg" => '获取订单详情成功',"order_data" => $order_data, "vehicle_data" => $vehicle_data, "departure_data" => $departure_data, "receiver_data" => $receiver_data], JSON_UNESCAPED_UNICODE);die();
        } catch (\Exception $e) {
        // 回滚事务
            Db::rollback();
            echo json_encode(["code" => 400, "msg" => '获取订单详情失败'], JSON_UNESCAPED_UNICODE);die();

        }
    }



    /**
     * 添加用户地址信息
     *dev.ziwudiche.com/api/order/addaddress
     * @param string $name 姓名
     * @param string $tel 手机号
     * @param array $start_addr_code 地点行政编码
     * @param string $addr_details 详细地址
     */
    public function addaddress()
    {
        $uid = self::$uid;
        $name = input('name');
        $tel = input('tel');
        $addr_code = implode(',', input('addr_code/a'));
        $addr_details = input('addr_details');
        $ctime = date('Y-m-d H:i:s', time());
        $data = [
            "uid" => $uid,
            "name" => $name,
            "tel" => $tel,
            "addr_code" => $addr_code,
            "addr_details" => $addr_details,
            "ctime" => $ctime,
        ];
        $addressid = Db::name('address_information')->insertGetId($data);
        if ($addressid) {
            echo json_encode(["code" => 200, "msg" => '添加地址信息成功', "data" => $addressid], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 404, "msg" => '添加地址信息失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 添加用户车辆信息
     *dev.ziwudiche.com/api/order/addcars
     */
    public function addcars()
    {
        $uid = self::$uid;
        $brand = input('brand');
        $logo = input('logo');
        $vehicle_value = input('vehicle_value');
        $separation = input('separation');
        $departure_mode = input('departure_mode');
        $receiving_mode = input('receiving_mode');
        $frame_number = input('frame_number');

        $data = [
            "uid" => $uid,
            "brand" => $brand,
            "logo" => $logo,
            "vehicle_value" => $vehicle_value,
            "separation" => $separation,
            "departure_mode" => $departure_mode,
            "receiving_mode" => $receiving_mode,
            "frame_number" => $frame_number,
        ];
        $res = Db::name('cars')->insertGetId($data);
        if ($res) {
            echo json_encode(["code" => 200, "msg" => '添加地址信息成功', "data" => $res], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 404, "msg" => '添加地址信息失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }


    /**
     * 删除发车人信息
     *dev.ziwudiche.com/api/order/deleteaddress
     *
     * @param string $addressid 地址id
     *
     */
    public function deleteaddress(){
        $addressid=input('addressid');
        $res=Db::name('address_information')->where('id',$addressid)->delete();
        if ($res){
            echo json_encode(["code" => 200, "msg" => '删除地址信息成功'], JSON_UNESCAPED_UNICODE);die();
        }else{
            echo json_encode(["code" => 400, "msg" => '删除地址信息失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 删除车辆信息
     *dev.ziwudiche.com/api/order/deletecars
     *
     * @param string $addressid 地址id
     *
     */
    public function deletecars(){
        $id=input('id');
        $res=Db::name('cars')->where('id',$id)->delete();
        if ($res){
            echo json_encode(["code" => 200, "msg" => '删除车辆信息成功'], JSON_UNESCAPED_UNICODE);die();
        }else{
            echo json_encode(["code" => 400, "msg" => '删除车辆信息失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 修改发车人信息
     *dev.ziwudiche.com/api/order/editaddress
     * @param string $name 姓名
     * @param string $tel 手机号
     * @param array $addr_code 地点行政编码
     * @param string $addr_details 详细地址
     * @param string $addressid 地址id
     *
     */
    public function editaddress(){
        $addressid=input('addressid');
        $name = input('name');
        $tel = input('tel');
        $addr_code = implode(',', input('addr_code/a'));
        $addr_details = input('addr_details');
        $data = [
            "name" => $name,
            "tel" => $tel,
            "addr_code" => $addr_code,
            "addr_details" => $addr_details,
        ];
        $res=Db::name('address_information')->where('id',$addressid)->update($data);
        if ($res){
            echo json_encode(["code" => 200, "msg" => '修改地址信息成功'], JSON_UNESCAPED_UNICODE);die();
        }else{
            echo json_encode(["code" => 404, "msg" => '修改地址信息失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }


    /**
     * 获取用户地址信息列表
     *dev.ziwudiche.com/api/order/getaddresslist
     *
     */
    public function getaddresslist()
    {
        $uid = self::$uid;
        $data = Db::name('address_information')->where('uid', $uid)->select();
        if ($data || $data==[]) {
            echo json_encode(["code" => 200, "msg" => '获取用户地址信息列表成功', "data" => $data], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 400, "msg" => '获取用户地址信息列表失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 获取用户车辆信息列表
     *dev.ziwudiche.com/api/order/getcarslist
     *
     */
    public function getcarslist()
    {
        $uid = self::$uid;
        $data = Db::name('cars')->where('uid', $uid)->select();
        if ($data || $data==[]) {
            echo json_encode(["code" => 200, "msg" => '获取用户车辆信息列表成功', "data" => $data], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 400, "msg" => '获取用户车辆信息列表失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 获取用户地址信息详情
     *dev.ziwudiche.com/api/order/getaddressdetails
     *@param string $addressid 地址id
     */
    public function getaddressdetails()
    {
        $addressid=input('addressid');
        $data = Db::name('address_information')->where('id',  $addressid)->select();
        if ($data ) {
            echo json_encode(["code" => 200, "msg" => '获取用户地址信息详情成功', "data" => $data], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 400, "msg" => '获取用户地址信息详情失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 获取用户车辆信息详情
     *dev.ziwudiche.com/api/order/getcarsdetails
     *@param string $addressid 地址id
     */
    public function getcarsdetails()
    {
        $id=input('id');
        $data = Db::name('cars')->where('id',  $id)->find();
        if ($data ) {
            echo json_encode(["code" => 200, "msg" => '获取用户地址信息详情成功', "data" => $data], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 400, "msg" => '获取用户地址信息详情失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }


    /**
     *获取所有车辆品牌
     * dev.ziwudiche.com/api/order/getcarbrand
     *http://47.96.138.236/api/Order/getcarbrand
     *
     */
    public function getcarbrand()
    {

            $brand = Db::name('vehicle_brand')->where('status', 1)->field("oid,brand,logo")->select();
            if ($brand){
                echo json_encode(["code" => 200, "data" => $brand], JSON_UNESCAPED_UNICODE);die();
            }else{
                echo json_encode(["code" => 400, "msg" => '获取品牌失败'], JSON_UNESCAPED_UNICODE);die();
            }

    }

    /**
     *获取所有指定品牌的车系
     *
     * dev.ziwudiche.com/api/order/getcarseparation
     * @param string $brandoid 车辆品牌原始id
     *
     */
    public function getcarseparation()
    {
            $brandoid=input('brandoid');
            $separation = Db::name('vehicle_separation')->where('pid', $brandoid)->column('separation', 'id');
            if ($separation || $separation==[]){
                echo json_encode(["code" => 200, "data" => $separation], JSON_UNESCAPED_UNICODE);
            }else{
                echo json_encode(["code" => 400, "msg" => '获取车系失败'], JSON_UNESCAPED_UNICODE);die();
            }

    }


}